// 产品列表页面（精品花束）
var basePage = require('../../../common/BasePage');
var baseList = require('../../../common/BaseList');
Page({
    behaviors: [basePage, baseList],
    /**
     * 页面的初始数据
     */
    data: {
        checkMobile: false,
        checkwxAuth: false,
        /**单独访问某个产品 */
        pid: 0,
        /**显示加入购物车弹窗 */
        addCart: false,
        /**显示视频弹出层 */
        showVideo: false,
        /**选中的产品 */
        pdc: {},
        /**购买数量 */
        nums: 1,
        reqUrl: '/home/supplier/product/index?wh_id=1',
        reqData: {
            /**颜色id */
            color_id: 0,
            level: '',
        },
        /**颜色列表 */
        colorArr: [{
            color_id: 0,
            title: '全部'
        }],
        /**选中的颜色 */
        color: {
            color_id: 0,
            title: '颜色'
        },
        /**等级数组 */
        levelArr: [{
                text: '全部',
                value: ''
            },
            {
                text: 'AA',
                value: 'AA',
            },
            {
                text: 'A',
                value: 'A',
            },
            {
                text: 'B',
                value: 'B',
            },
            {
                text: 'C',
                value: 'C',
            },
            {
                text: '基地',
                value: '基地',
            },
            {
                text: 'D',
                value: 'D',
            },

        ],
        /**成熟度 */
        maturityArr: [{
                text: '全部',
                value: ''
            }, {
                text: '生',
                value: '生',
            },
            {
                text: '中熟',
                value: '中熟',
            },
            {
                text: '偏熟',
                value: '偏熟',
            },
            {
                text: '熟',
                value: '熟',
            },
        ],
        /**促销选项 */
        typeArr: [{
                text: '全部',
                value: ''
            },
            {
                text: '促销',
                value: 2
            },
        ],

        /**
         * 排序选项
         */
        orderArr: [{
                text: '最新',
                value: 'is_new'
            },
            {
                text: '智能排序',
                value: 'smart'
            },
            {
                text: '人气最高',
                value: 'sales'
            },
        ],
        uid: "",
        productId2: "",
        whType: "flower",
        wh_id: 1,
        detaiInfo:{},//涨跌信息
        screenPopupTop:0,
        screenPopupMaxHeight:0,
        screenArr:[],//筛选
        screenIndex:-1,
        screenType:"",
        screenPopupShow:false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log("options", options)
        if (options.uid) {
            this.setData({
                uid: options.uid
            })
        }
        if (options.title) {
            wx.setNavigationBarTitle({
                title: options.title,
            });
        }
        // console.log("options.this.data.wh_id", options.wh_id);
        let wh_id = options.wh_id || getApp().globalData.warehouse.wh_id;
        this.setData({
            wh_id:wh_id
        })
        // this.data.wh_id = wh_id
        this.data.reqUrl = '/home/supplier/product/index?wh_id=' + wh_id;
        if (options.whType == 1) {
            this.data.reqUrl = '/home/wh/product/index?wh_id=' + wh_id;
            this.setData({
                whType: "pindan"
            })
        }
        options.supplier_id ? this.data.reqUrl = this.data.reqUrl + "&supplier_id=" + options.supplier_id : '';
        options.cate_id ? this.data.reqUrl = this.data.reqUrl + "&cate_id=" + options.cate_id : '';
        options.pid ? this.data.pid = options.pid : '';
        // options.product_id ? this.data.product_id = options.product_id : '';
        // options.product_id ? this.data.productId2 = options.product_id : '';
        this.setData({
            product_id:options.product_id?options.product_id : '',
            product_id2:options.product_id?options.product_id : '',
        })
        if(options.product_id){
            this.getDetail()
        }
        
        if (options.so) { //搜索词
            this.data.reqData.so = options.so;
            this.setData({
                reqData: this.data.reqData
            })
            // console.log("options.so", this.data.reqData.so)
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.data.current_page = 0;
        this.req_items();
        
    },
    onReachBottom: function () {
        console.log("触底");
        this.req_items()
    },
    getDetail(){
        this.request({
            url:this.data.host+"/home/index/rateProduct",
            data:{
                wh_id:this.data.wh_id,
                product_id:this.data.product_id
            }
        },res=>{
            var info=res.data
            if(info.yesterday_price && info.yesterday_price!=0 &&info.yesterday_price!='0.00'){
                info.changePrice=(info.today_price-info.yesterday_price).toFixed(2)
            }else{
                info.changePrice=0
            }
            this.setData({
                detaiInfo:info
            })
        })
    },
    /**
     * 请求后台列表数据
     */
    req_items() {
        let data = this.data;
        if (data.pages > data.current_page) {
            data.reqData.page = (data.current_page * 1) + 1;
            if (this.data.pid) { //第一次只筛选某个产品
                data.reqData.pid = this.data.pid;
                this.data.pid = 0;
            }
            if (this.data.product_id) { //第一次只筛选某个产品
                data.reqData.product_id = this.data.product_id;
                this.data.product_id = 0;
            }
            // else{
            //   data.reqData.pid=0
            // }
            this.request({
                url: this.data.host + data.reqUrl,
                data: data.reqData
            }, this.get_items_ok)
        }
    },
    /**
     * 获得列表数据
     */
    get_items_ok(res) {
        this.data.pages = res.pages;
        this.data.current_page = res.current_page;
        console.log("get_items_ok", res);
        res.data.map((res, index, arr) => {
            this.init_val(res, index, arr)
        })
        let itemArr = this.data.itemArr;
        res.current_page == 1 ? itemArr = res.data : itemArr = itemArr.concat(res.data);
        this.setData({
            itemArr,
            colorArr: [{
                color_id: 0,
                title: '全部'
            }, ...res.color_list]
        });
        wx.stopPullDownRefresh({
            success: (res) => {},
        })
    },
    init_val(val, index, arr) {
        val.thumb = this.get_thumb(val.product_img);
    },
    /**
     * 显示商家基地视频
     * @param {event} e 
     */
    show_video(e) {
        // console.log("show_video", e);
        // console.log(this.data.imgHost + '/' + e.detail);
        this.setData({
            showVideo: this.data.imgHost + '/' + e.detail
        })
    },
    onCloseCart() {
        this.setData({
            addCart: false
        })
    },
    /**
     *加入购物车事件
     */
    add_cart_click(e) {
        console.log(e);
        this.setData({
            addCart: true,
            pdc: e.detail,
            nums: 1
        });
    },
    // 加入常购
    addChanggou(e) {
        var item=e.detail
        this.request({
            url: this.data.host + '/home/often/addToOften',
            data: {
                pid:item.pid
            },
            loadingTip: '正在提交',
            method: "post"
        }, this.add_often_ok);
    },
    add_often_ok(res) {
        wx.showModal({
            cancelText: '继续添加',
            confirmText: '常购清单',
            content: '是否前往常购清单',
            showCancel: true,
            title: '设置成功',
            success: (result) => {
                if (result.confirm) {
                    // console.log("跳转完善页面");
                    wx.navigateTo({
                        url: '/pages/cls/often/List',
                    })
                }
            },
        })
    },
    /**
     * 添加产品到购物车
     */
    add_cart() {
        var url = "/home/cart/addToCart"
        if (this.data.whType == "pindan") {
            url = "/home/wh/cart/addToCart"
        }
        this.request({
            url: this.data.host + url,
            data: {
                pid: this.data.pdc.pid,
                nums: this.data.nums,
                wh_id: this.data.wh_id
            },
            method: 'post'
        }, this.add_cart_ok);
    },
    add_cart_ok(res) {
        this.setData({
            addCart: false
        })
        wx.showToast({
            title: res.msg,
            icon: 'success'
        })
    },
    buy_good() {
        console.log("立即购买", this.data.pdc)
        let pdc = this.data.pdc
        let data = {
            pid: this.data.pdc.pid,
            nums: this.data.nums,
            wh_id: this.data.wh_id
        }
        var url = "/home/flower/preInfo"
        if (this.data.whType == "pindan") {
            url = "/home/wh/order/preInfo"
        } else {
            data.from = "flower"
        }

        this.request({
            url: this.data.host + url,
            data: data,
            method: 'get'
        }, res => {
            this.setData({
                addCart: false
            })
            res.data.cashier_decca = this.get_thumb(res.cashier_decca, 'wide');
            let that = this;
            wx.navigateTo({
                // url: '/pages/order_confirm/order_confirm',
                url: '/pages/neworder_confirm/order_confirm',
                success: function (obj) {
                    // 通过eventChannel向被打开页面传送数据

                    obj.eventChannel.emit('orderData', {
                        wh_id: that.data.wh_id,
                        // index: that.data.areaData[that.data.tabIndex].index,
                        data: res.data,
                        m_addr: res.m_addr,
                        activeCar: that.data.whType,
                        wuliu: res.data.freight_list,
                        specialList: res.data.extra_list,
                        pack_list: res.data.pack_list,
                        buyType: 1,
                        order_pei_type: res.order_pei_type,
                        orderWarehouse:res.warehouse
                    })
                }
            })
        });
    },
    nums_change(e) {
        // this.data.nums = e.detail;
        this.setData({
            nums: e.detail
        })
        // console.log("nums_change",e)
    },
    /**
     * 收藏点击
     */
    collect_click(e) {
        console.log("collect_click", e);
        let pdc = e.detail;
        let index = e.currentTarget.dataset.index;
        let status = pdc.collected ? 0 : 1;
        this.request({
            url: this.data.host + '/home/user/collect/collect',
            data: {
                status: status,
                can_id: pdc.pid,
                type: 1
            },
            method: 'post'
        }, res => {
            console.log("collect_ok", res);
            let item = this.data.itemArr[index];
            item.collected = status;
            item.collects = status ? (item.collects * 1) + 1 : item.collects - 1;
            this.setData({
                itemArr: this.data.itemArr
            })
        });
    },
    /**选中颜色 */
    color_click(e) {
        console.log("color_click", e);
        let reqData = this.data.reqData;
        let color = e.currentTarget.dataset.color;
        reqData.color_id = color.color_id;
        this.setData({
            reqData,
            color
        });
        this.selectComponent('#color').toggle();
        /**更新列表 */
        this.data.current_page = 0;
        this.req_items();
    },
    /**
     * 筛选项变化
     */
    req_change(e) {
        // console.log("level_change", e);
        // this.data.reqData[e.currentTarget.dataset.field] = e.detail;
        this.data.reqData[this.data.screenType] = e.currentTarget.dataset.value;
        this.setData({
            screenPopupShow:false,
            screenIndex:e.currentTarget.dataset.index
        })
        this.data.current_page = 0;
        this.req_items();
    },
    onShowScreen(e){
        var field=e.currentTarget.dataset.field
        var arr=e.currentTarget.dataset.arr
        var screenPopupShow=false
        if(this.data.screenType==field){
            screenPopupShow=false
            this.setData({
                screenType:""
            })
        }else{
            screenPopupShow=true
            this.setData({
                screenType:field,
            })
        }
        this.setData({
            screenArr:this.data[arr],
            screenIndex:-1,
            screenPopupShow:screenPopupShow
        })
    },
    hideScreenPopup(){
        this.setData({
            screenPopupShow:false
        })
    },
    /**确认搜索内容 */
    search_click(e) {
        console.log("search_click", e);
        this.data.current_page = 0;
        this.data.reqData = {
            so: e.detail
        }
        this.req_items();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        setTimeout(() => {
            //获取筛选栏位置信息
            this.getRect('.dropdown').then(res => {
               
                // if (!res) {
                //     res = { bottom: 210 };
                // }
                if (!res) return;
                let screenPopupMaxHeight = wx.getSystemInfoSync().windowHeight - res.bottom;
                this.setData({ screenPopupTop: res.bottom, screenPopupMaxHeight });
                console.log("screenPopupMaxHeight",screenPopupMaxHeight)
            });

        }, 1000);
    },
    //获取节点位置信息
    getRect(selector) {
        let that = this;
        return new Promise(function (resolve) {
            that.createSelectorQuery()
                .select(selector)
                .boundingClientRect()
                .exec(function (rect) {
                    if (rect === void 0) {
                        rect = [];
                    }
                    return resolve(rect[0]);
                });
        });
    },


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    onShareAppMessage(res) {
        console.log("onShareAppMessage", res);
        let path = "/pages/cls/pdcList/Index?uid=" + getApp().globalData.userInfo.uid + '&product_id=' + this.data.productId2+"&wh_id="+this.data.wh_id;
        let title = "";
        if (res && res.target) {
            let pid = res.target.dataset.pid;
            let product_id = res.target.dataset.product_id;


            if (pid) {
                path = '/pages/cls/pdcList/Index?pid=' + pid + '&product_id=' + product_id + '&uid=' + getApp().globalData.userInfo.uid;
                title = "您的朋友向你推荐了一款鲜花"
            }

        }
        console.log("onShareAppMessagepath", path);
        return {
            title: title,
            path: path,
            // promise 
        }
    }
})